import express from 'express'
import dayjs from 'dayjs'
import jwt from 'jsonwebtoken'
import { get } from '../../../common/conf'

const router = express.Router()
const USER_KEY = 'E_USER'
const djs = dayjs()
let app
let client

const resObj = { code: 500, message: '失败', data: {} }

const result = (code, message, data) => {
  resObj.code = code
  resObj.message = message
  resObj.data = data || {}
}

const genToken = (user) => {
  const secret = get('auth.secret')
  const token = 'Bearer ' + jwt.sign(
    {
      username: user.username
    },
    secret,
    {
      expiresIn: 3 * 60 * 60
    }
  )
  return token
}

// Login: /login
router.post('/login', async (req, res) => {
  const { username, password } = req.body
  try {
    console.log(client)
    const have = await client.hExists(USER_KEY, username)
    if (have) {
      const info = JSON.parse(await client.hGet(USER_KEY, username))
      if (info.password !== password) {
        result(401, '密码不正确')
      } else {
        console.log('Login User: ', info)
        result(200, '登录成功', genToken(info))
      }
    } else {
      result(404, '用户不存在')
    }
  } catch (error) {
    result(500, '失败', error.message)
  } finally {
    res.send(resObj)
  }
})

// Register: /reg
router.post('/reg', async (req, res) => {
  const { username, password } = req.body
  try {
    const have = await client.hExists(USER_KEY, username)
    if (have) {
      result(500, '用户名已存在')
    } else {
      const info = JSON.stringify({
        username,
        password,
        create: djs.format('YYYY-MM-DD HH:mm:ss'),
        update: '',
        login: '',
        enabled: true
      })
      const r = await client.hSet(USER_KEY, username, info)
      if (r === 1) {
        result(200, '注册成功')
      } else {
        result(500, '注册失败')
      }
    }
  } catch (error) {
    result(500, '失败', error.message)
  } finally {
    res.send(resObj)
  }
})

router.get('/token', async (req, res) => {
  if (!req.auth.username) {
    result(401, 'invalid token...')
  } else {
    result(200, 'Token Pass', req.auth)
  }
  res.send(resObj)
})

router.get('/cookie', (req, res) => {
  console.log('Cookies: ', req.cookies)
  console.log('Signed Cookies: ', req.signedCookies)
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})

export default (_app, _client) => {
  app = _app
  client = _client
  return router
}
